import os
import shutil
from loguru import logger

class ToolLifecycleManager:
    def __init__(self, tools_info_path="tools/tools_info.md"):
        self.tools_info_path = tools_info_path
        self.builtin_tools_dir = os.path.join("tools", "builtin")
        self.generated_tools_dir = os.path.join("tools", "generated")
        self.deprecated_tools_dir = os.path.join("old_versions", "tools")
        os.makedirs(self.deprecated_tools_dir, exist_ok=True)

    def _update_tools_info(self, tool_name: str, action: str):
        try:
            with open(self.tools_info_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()

            new_lines = []
            tool_section_found = False
            for i, line in enumerate(lines):
                if line.strip().lower().startswith(f"### {tool_name.lower()}"):
                    tool_section_found = True
                    if action == "remove":
                        # Skip this section until the next ### or end of file
                        logger.info(f"Removing section for tool '{tool_name}' from tools_info.md")
                        for j in range(i, len(lines)):
                            if lines[j].strip().startswith("### ") and j > i:
                                break
                        continue # Skip adding lines for this tool
                    elif action == "add":
                        # If adding, we'll append it later if not found
                        pass
                new_lines.append(line)
            
            if action == "add" and not tool_section_found:
                # Append new tool description if not found
                new_lines.append(f"\n### {tool_name}\n")
                new_lines.append(f"**Description:** This is a {tool_name} tool.\n")
                new_lines.append(f"**Usage:** {tool_name}(...)\n")
                logger.info(f"Adding section for tool '{tool_name}' to tools_info.md")

            with open(self.tools_info_path, 'w', encoding='utf-8') as f:
                f.writelines(new_lines)
            logger.info(f"Successfully updated {self.tools_info_path} for tool '{tool_name}' ({action}).")
        except Exception as e:
            logger.error(f"Error updating tools_info.md for tool '{tool_name}': {e}", exc_info=True)

    def promote_tool(self, tool_name: str) -> bool:
        source_path = os.path.join(self.generated_tools_dir, f"{tool_name}.py")
        destination_path = os.path.join(self.builtin_tools_dir, f"{tool_name}.py")

        if not os.path.exists(source_path):
            logger.warning(f"Tool '{tool_name}' not found in generated tools directory: {source_path}")
            return False

        try:
            shutil.move(source_path, destination_path)
            self._update_tools_info(tool_name, "add")
            logger.info(f"Tool '{tool_name}' promoted from generated to builtin.")
            return True
        except Exception as e:
            logger.error(f"Error promoting tool '{tool_name}': {e}", exc_info=True)
            return False

    def deprecate_tool(self, tool_name: str) -> bool:
        possible_paths = [
            os.path.join(self.builtin_tools_dir, f"{tool_name}.py"),
            os.path.join(self.generated_tools_dir, f"{tool_name}.py")
        ]
        
        found_path = None
        for path in possible_paths:
            if os.path.exists(path):
                found_path = path
                break

        if not found_path:
            logger.warning(f"Tool '{tool_name}' not found in builtin or generated tools directories.")
            return False

        try:
            destination_path = os.path.join(self.deprecated_tools_dir, f"{tool_name}.py")
            shutil.move(found_path, destination_path)
            self._update_tools_info(tool_name, "remove")
            logger.info(f"Tool '{tool_name}' deprecated and moved to {self.deprecated_tools_dir}.")
            return True
        except Exception as e:
            logger.error(f"Error deprecating tool '{tool_name}': {e}", exc_info=True)
            return False
